package com.ruoyi.project.common;

import com.aliyun.oss.*;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.*;
import com.ruoyi.project.common.domain.UploadTokenVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.*;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

import static com.ruoyi.framework.web.domain.AjaxResult.success;


@Controller
@RequestMapping(path = "/file")
public class FileController {

    private static final Logger loger = LoggerFactory.getLogger(FileController.class);

    private static String endpoint = "oss-cn-beijing.aliyuncs.com";
    private static String accessKeyId = "LTAIfSEAHovXQn9Y";
    private static String accessKeySecret = "mtWg7jeBnsONd8vpq9hW14nzxA2bXe";
    private static String bucketName = "tm-city";


    @RequestMapping(path = "/getUploadToken", method = RequestMethod.GET)
    @ResponseBody
    public UploadTokenVo getUploadToken(@RequestParam("fileName") String fileName) throws UnsupportedEncodingException {
        // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
        String uploadUrl = "http://" + bucketName + "." + endpoint;

        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 生成过期时间
        LocalDateTime ldt = LocalDateTime.now().plusMinutes(10);
        Instant instant = ldt.toInstant(ZoneOffset.ofHours(8));
        Date expireDate = Date.from(instant);

        // 生成key
        String ext = fileName.substring(fileName.lastIndexOf("."));
        String key = "test0804/user-dir"+UUID.randomUUID().toString() + ext;

        // 上传Policy
        final int minFileSize = 1; // 1Byte
        final int maxFileSize = 1024*1024*10; //
        PolicyConditions policyConds = new PolicyConditions();

        //policyConds.addConditionItem(PolicyConditions.COND_KEY, key);
        policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, key);
        // 文件大小限制
        policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, minFileSize, maxFileSize);
        String postPolicy = client.generatePostPolicy(expireDate, policyConds);
        String encodedPolicy = BinaryUtil.toBase64String(postPolicy.getBytes("utf-8"));
        // 签名
        String postSignature = client.calculatePostSignature(postPolicy);
        // 重要，OSSClient用完要关掉，不然会内存泄漏
        client.shutdown();

        UploadTokenVo uploadTokenVo = new UploadTokenVo();
        uploadTokenVo.setAccessKey(accessKeyId);
        uploadTokenVo.setKey(key);
        uploadTokenVo.setPolicy(encodedPolicy);
        uploadTokenVo.setUploadUrl(uploadUrl);
        uploadTokenVo.setSignature(postSignature);

        return uploadTokenVo;
    }


}
